<script setup lang='ts' name="company-org">
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'

import { delCompanyOrg, getCompanyOrg, useGetCatTypeDictInfo } from '@fl/api/iam-api'

import { addCompany, delCompany, getCompanyByLoginUser, getCompanyList } from '@fl/api/joint-api'
import ButtonItem from '@fl/components/button-item.vue'
import { formatTime } from '@fl/utils'
import { ElButton, ElCard, ElCol, ElDatePicker, ElForm, ElFormItem, ElInput, ElRow, ElTag } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import type { IRowV0 } from './types'

import AddArea from './component/add-area.vue'
import AddBusiness from './component/add-business.vue'
import DetailItem from './component/detail.vue'
import DetailEdit from './component/add.vue'
import { useDicts } from './hooks/use-dicts'
import { useTable } from './hooks/use-table'
import { useUserStore } from '@fl/store/modules/user'

const { companyAuditStatus, useDict } = useDicts()

const { managerBtns, adminBtns, gridOptions } = useTable()

function getBtns(row: any) {
    if (isAdmin.value) {
        if (row?.auditStatus === '2') {
            return adminBtns.filter((item: any) => item.value !== 'edit')
        }
        return adminBtns
    }
    else {
        if (row?.auditStatus === '2') {
            return managerBtns.filter((item: any) => item.value !== 'edit')
        }
        return managerBtns
    }
}

const defaultTime = ref<[Date, Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
])

const userStore = useUserStore()
const isAdmin = ref<boolean>(userStore.getUserInfo?.userFlag === '1')

const state = {
    legalName: '',
    createTime: '',
    auditStatus: '',
    companyName: '',
}

const form = ref({ ...state })

const router = useRouter()
const route = useRoute()
const detail = ref<any>({})

const detailItemRef = ref()
const showId = ref('')
const showAddArea = ref(false)
const showAddBusiness = ref(false)
const hasCompany = ref(true)
const xGrid = ref<VxeGridInstance<IRowV0>>()
const startIdx = ref(0)

const gridEvents: VxeGridListeners<IRowV0> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
            startIdx.value = (currentPage - 1) * pageSize
        }
        getData()
    },
}

const activeView = ref('list') // 默认值：'list' | 'edit' | 'detail'

const showList = computed(() => activeView.value === 'list')
const showEdit = computed(() => activeView.value === 'edit')
const showDetail = computed(() => activeView.value === 'detail')

async function getData(currentPage?: number, pageSize?: number) {
    if (currentPage && pageSize) {
        gridOptions.pagerConfig.currentPage = currentPage
        gridOptions.pagerConfig.pageSize = pageSize
    }

    gridOptions.loading = true
    let res: { records: any[], total: number } = { records: [], total: 0 }
    if (isAdmin.value) {
        res = await getCompanyList({
            ...form.value,
            endTime: formatTime(form.value.createTime[1], 'yyyy-MM-dd HH:mm:ss'),
            pageNum: gridOptions.pagerConfig.currentPage,
            pageSize: gridOptions.pagerConfig.pageSize,
            startTime: formatTime(form.value.createTime[0], 'yyyy-MM-dd HH:mm:ss'),
        })
    }
    else {
        const userCompanyDetail = await getCompanyByLoginUser()
        if (userCompanyDetail?.id) {
            hasCompany.value = true
            res.records = [userCompanyDetail]
            if (userStore.getUserInfo?.userStep === '3') {
                activeView.value = 'detail'
                showId.value = String(userCompanyDetail?.id)
            }
        }
        else {
            hasCompany.value = false
        }
    }
    if (res) {
        console.log('index', res)
        gridOptions.loading = false
        gridOptions.pagerConfig.total = res.total
        gridOptions.data = res?.records || []
    }
}

function reset() {
    form.value = { ...state }
    getData()
}

async function doAction(item: any, row: any) {
    switch (item.value) {
        case 'edit':
            activeView.value = 'edit'
            showId.value = String(row.id)
            // router.push(`/joint/business-management/add-enterprise?id=${row.id}`)
            break
        case 'view':
            activeView.value = 'detail'
            showId.value = String(row.id)
            break
        case 'area':
            detail.value = cloneDeep(row)
            showAddArea.value = true
            showId.value = String(row.id)
            break
        case 'business':
            detail.value = cloneDeep(row)
            showAddBusiness.value = true
            showId.value = String(row.id)
            break
        case 'delete':
            delCompanyOrg(String(row.id)).then((res) => {
                if (res.code === 200) {
                    ElMessage.success('操作成功')
                    setTimeout(() => {
                        getData(1, 10)
                    }, 500)
                }
            })
            break

        default:
            break
    }
}

function doAdd() {
    showId.value = ''
    activeView.value = 'edit'
    // router.push('/joint/business-management/add-enterprise')
}

function goTo(type: 'list' | 'edit' | 'detail') {
    // console.log('🚀 ~ goTo ~ type:', type)
    activeView.value = type
}

// function assignmentArea() {
//     const rows = xGrid.value?.getCheckboxRecords()
//     if (rows?.length === 0) {
//         ElMessage.warning('请至少选择一条数据')
//         return
//     }
//     const ids = rows?.map(item => item?.id).join(',')

//     showAddArea.value = true
//     showId.value = String(ids)
// }
// function assignmentCard() {
//     const rows = xGrid.value?.getCheckboxRecords()
//     if (rows?.length === 0) {
//         ElMessage.warning('请至少选择一条数据')
//         return
//     }
//     const ids = rows?.map(item => item?.id).join(',')
//     showId.value = String(ids)
//     showAddBusiness.value = true
// }

function toggleAllCheckboxEvent() {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleAllCheckboxRow()
}

function toggleCheckboxEvent(row) {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleCheckboxRow(row)
}

function init(val) {
    const id = val.query?.id
    console.log('🚀 ~ init ~ id:', id)

    if (id) {
        activeView.value = 'edit'
        showId.value = String(id)
    }
    
    getData()
}

watch(showList, (val: boolean) => {
    if (val)
        reset()
})

watch(route, (val: any) => {
    init(val)
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <div v-if="showList">
        <ElCard v-if="isAdmin"
                mb-20
        >
            <ElForm :inline="true"
                    :model="form"
                    label-width="100"
                    class="query_form"
            >
                <ElRow>
                    <ElCol :span="8">
                        <ElFormItem label="企业名称"  style="width: 100%">
                            <ElInput v-model="form.companyName"
                                     placeholder="请输入"
                                     clearable
                            />
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="8">
                        <ElFormItem label="企业法人"  style="width: 100%">
                            <ElInput v-model="form.legalName"
                                     placeholder="请输入"
                                     clearable
                                    
                            />
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="8">
                        <ElFormItem label="审核状态"  style="width: 100%">
                            <ElSelect v-model="form.auditStatus"
                                      clearable
                                      style="width: 100%"
                            >
                                <ElOption v-for="item in companyAuditStatus"
                                          :key="item.value"
                                          :value="item.value"
                                          :label="item.label"
                                />
                            </ElSelect>
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="8">
                        <ElFormItem label="创建时间"  style="width: 100%">
                            <ElDatePicker v-model="form.createTime"
                                          :default-time="defaultTime"
                                          type="daterange"
                                          range-separator="-"
                                          format="YYYY/MM/DD"
                                          start-placeholder="开始日期"
                                          end-placeholder="结束日期"
                            />
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="8"
                           :offset="8"
                           style="text-align: right;"
                    >
                        <ElButton type="primary"
                                  @click="getData(1, 10)"
                                  
                            class="w-60"
                        >
                            搜索
                        </ElButton>

                        <ElButton @click="reset" class="w-60">
                            重置
                        </ElButton>

                        <!-- <ElButton @click="goTo">
                            跳转
                        </ElButton> -->
                    </ElCol>
                </ElRow>
            </ElForm>
        </ElCard>

        <ElCard>
            <!-- <div v-if="isAdmin"
                 class="mb-20"
            >
                <ElButton type="primary"
                          @click="assignmentArea"
                >
                    分配区域
                </ElButton>

                <ElButton type="primary"
                          @click="assignmentCard"
                >
                    分配卡片
                </ElButton>
            </div> -->

            <ElButton v-if="!isAdmin && !hasCompany"
                      class="mb-20"
                      type="primary"
                      @click="doAdd"
            >
                + 添加企业
            </ElButton>
            <!-- 列表 -->
            <vxe-grid ref="xGrid"
                      v-bind="gridOptions"
                      :seq-config="{ startIndex: startIdx }"

                      v-on="gridEvents"
            >
                <template #checkbox_header="{ checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleAllCheckboxEvent"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #checkbox_cell="{ row, checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleCheckboxEvent(row)"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #status="{ row }">
                    {{ useDict('companyAuditStatus', row?.auditStatus) }}
                </template>

                <template #operate="{ row }">
                    <ButtonItem :btns="getBtns(row)"
                                @btn-click="doAction($event, row)"
                    />
                </template>
            </vxe-grid>
        </ElCard>
    </div>

    <DetailItem v-if="showDetail"
                ref="detailItemRef"
                v-model="showList"
                :show-id="showId"
                @confirm="getData"
                @goto="goTo"
    />

    <DetailEdit v-if="showEdit"
                ref="detailItemRef"
                v-model="showEdit"
                :show-id="showId"
                @confirm="getData"
                @goto="goTo"
    />

    <AddArea v-if="showAddArea"
             key="addArea"
             v-model="showAddArea"
             :show-id="showId"
             :data="detail"
             @confirm="getData"
    />

    <AddBusiness v-if="showAddBusiness"
                 key="addArea"
                 v-model="showAddBusiness"
                 :show-id="showId"
                 :data="detail"
                 @confirm="getData"
    />
</template>

<style lang="less" scoped>
// .query_form {
//     :deep(.el-form-item__content) {
//         width: 260px;
//     }
// }
:deep(.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
